//
//  ProfileView.swift
//  Tiktok
//
//  Created by xmd on 10/27/20.
//

import SwiftUI

struct ProfileView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @EnvironmentObject var imageProvider: ImageProvider
    @ObservedObject var model = UserProfileVM()
    @State var scrollOffsetY: CGFloat = 0
    @State var tabsViewOffsetY: CGFloat = 1
    @State var currentTabIndex = 0
    
    
    var musicList = userMusicList.music
    let colorWhite = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    let colorDarkWhite = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7105361729)
    
    var scrollContentHeight: CGFloat {
        tabsViewHeight + titleBarHeight + CGFloat(musicList.count * (80 + 14))
    }
    
    var body: some View {
        ZStack(alignment: .topLeading) {
            VStack(spacing: 0) {
                ZStack(alignment: .leading) {
                    HStack {
                        Text(self.model.nickname)
                            .offset(y: -25)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .foregroundColor(.white)
                    .background(Color(#colorLiteral(red: 0.09028358012, green: 0.0940457657, blue: 0.137185663, alpha: 1)))
                    .opacity(self.scrollOffsetY > 0 ? Double(self.scrollOffsetY / 240) : 0)
                    Button(action: {
                        self.presentationMode.wrappedValue.dismiss()
                    }, label: {
                        Image("return_icon40x40")
                    })
                    .buttonStyle(PlainButtonStyle())
                    .offset(x: 16, y: -25)
                }
                .frame(height: titleBarHeight)
                if tabsViewOffsetY <= titleBarHeight {
                    HStack {
                        let titles = ["音乐", "作品", "动态", "喜欢"]
                        TabsView(
                            countTabs: titles.count,
                            currentTabIndex: $currentTabIndex
                        ){ i in
                            Text(titles[i])
                        }.foregroundColor(.white)
                    }
                    .padding(.horizontal, 16)
                    .frame(height: tabsViewHeight)
                    .background(Color(#colorLiteral(red: 0.09028358012, green: 0.0940457657, blue: 0.137185663, alpha: 1)))
                }
            }
            .zIndex(2)
            ScrollView(.vertical, showsIndicators: false) {
                ZStack(alignment: .top) {
                    GeometryReader { geometry -> AnyView in
                        let frame = geometry.frame(in: .global)
                        DispatchQueue.main.async {
                            self.scrollOffsetY = -frame.minY
                        }
                        let height = geometry.size.height + (frame.minY < 0 ? 0 : frame.minY)
                        let width = geometry.size.width + (frame.minY < 0 ? 0 : (geometry.size.width / 200 * frame.minY))
                        return AnyView(
                            ZStack(alignment: .center) {
                                OptionalImage(uiImage: imageProvider.get(from: model.backgroundUrl))
                                    .frame(width: width, height: height)
                                    .clipped()
                            }
                            .frame(width: geometry.size.width, height: height, alignment: .center)
                            .offset(y: frame.minY < 0 ? 0 : -frame.minY)
                        )
                    }
                }
                .frame(height: 200, alignment: .center)
                VStack {
                    FollowTheUserView(avatarImageUrl: model.avatarUrl)
                    ZStack() {
                        Text(model.nickname)
                            .font(.system(size: 30))
                    }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding(.vertical, 10)
                    HStack {
                        Image("im_musicianVerified20x20")
                        Text("抖音音乐人")
                        Spacer()
                        Image("iconProfileToutiao20x20")
                        Text("头条新闻")
                    }
                    Divider()
                        .padding(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
                    HStack {
                        Text(model.userDesc)
                        Spacer()
                    }
                    HStack {
                        Tag {
                            Image("icon_girl12x12")
                            Text(model.age)
                        }
                        Tag {
                            Text(model.location)
                        }
                        Tag {
                            Text(model.university)
                        }
                        Spacer()
                    }
                    HStack {
                        HStack(spacing: 0) {
                            Text(model.likes)
                                .foregroundColor(Color( #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
                            Text("获赞")
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7008142606)))
                        }
                        
                        HStack(spacing: 0) {
                            Text(model.following)
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
                            Text("关注")
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7008142606)))
                        }
                        HStack(spacing: 0) {
                            Text(model.fans)
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
                            Text("粉丝")
                                .foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7008142606)))
                        }
                        Spacer()
                    }
                    
                    HStack {
                        GeometryReader { geo -> AnyView in
                            let frame = geo.frame(in: .global)
                            DispatchQueue.main.async {
                                self.tabsViewOffsetY = frame.minY
                            }
                            let titles = ["音乐", "作品", "动态", "喜欢"]
                            return AnyView(
                                TabsView(
                                    countTabs: titles.count,
                                    currentTabIndex: $currentTabIndex
                                )
                                { Text(titles[$0]) }
                                .foregroundColor(.white)
                            )
                        }
                    }
                    .frame(height: tabsViewHeight)
                    .background(Color(#colorLiteral(red: 0.09028358012, green: 0.0940457657, blue: 0.137185663, alpha: 1)))
                    VStack {
                        ForEach((0..<musicList.count)) { i in
                            MusicItemView(music: musicList[i])
                        }
                    }
                }
                .foregroundColor(Color(colorDarkWhite))
                .padding(.horizontal, 16)
                Rectangle().fill(Color.clear).frame(height: (UIScreen.main.bounds.height > scrollContentHeight) ? UIScreen.main.bounds.height - scrollContentHeight : 0)
            }
            
            
        }
        .background(Color(#colorLiteral(red: 0.09028358012, green: 0.0940457657, blue: 0.137185663, alpha: 1)))
        .edgesIgnoringSafeArea(.vertical)
        .navigationBarTitle("")
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
    }

    struct Tag<Content>: View where Content: View{
        var content: Content
        
        init(@ViewBuilder content: () ->  Content) {
            self.content = content()
        }
        var body: some View {
            HStack {
                content
            }
            .padding(5)
            .background(Color(#colorLiteral(red: 0.2706356645, green: 0.2744644582, blue: 0.30971843, alpha: 1)))
            .cornerRadius(5)
        }
    }

    private static var tabBarHeight: CGFloat = 30
    private let titleBarHeight: CGFloat = 150
    private let tabsViewHeight: CGFloat = 40
}

// MARK: - Tabs view for navigation

struct TabsView<ItemView>: View where ItemView: View{
    var countTabs:Int = 0
    @Binding var currentTabIndex: Int
    @State var tabDims: [Int:CGRect] = [:]
    
    var itemViewProvider: (_ index: Int) -> ItemView
    
    var body: some View {
        GeometryReader { geometry in
            let itemViewWidth = geometry.size.width / CGFloat(countTabs)
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 0) {
                    ForEach((0..<countTabs)) { i in
                        ZStack(alignment: .center) {
                            itemViewProvider(i)
                        }
                        .frame(width: itemViewWidth)
                        .onTapGesture {
                            withAnimation {
                                currentTabIndex = i
                            }
                        }
                    }
                }.frame(maxHeight: .infinity)
                ZStack(alignment: .leading) {
                    Divider()
                    Rectangle()
                        .fill(Color(#colorLiteral(red: 0.9803921569, green: 0.8078431373, blue: 0.0862745098, alpha: 1)))
                        .frame(width: itemViewWidth, height: 1.5)
                        .offset(x: itemViewWidth * CGFloat(currentTabIndex))
                }
            }
        }
    }
}

// MARK: - User music list item

struct MusicItemView: View {
    @EnvironmentObject var imageProvider: ImageProvider
    var model: Music
    init(music: Music) {
        self.model = music
    }
    var body: some View {
        HStack {
            ZStack {
                OptionalImage(uiImage: imageProvider.get(from: model.coverThumb.urlList.first!))
                    .frame(width: 80, height: 80)
                    .cornerRadius(5)
            }
            VStack(alignment: .leading) {
                HStack {
                    Image("icon_home_original_musicnote16x16")
                    Text(model.title).foregroundColor(Color.white)
                }
                HStack {
                    Text("\(model.userCount)").foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7105361729)))
                    Text("个视频使用").foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7105361729)))
                }
                Text(model.duration.toMusicDurationString()).foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.7105361729)))
            }
            Spacer()
            HStack(spacing: 10) {
                Image("icon_white_nocollection24x24")
                Image("icon_ost_detail24x24")
            }
        }
    }
}


// MARK: - Follow the user view

struct FollowTheUserView : View {
    @EnvironmentObject var imageProvider: ImageProvider
    @State var isFollowing = false
    @State var isExpanded = false
    var avatarImageUrl: String
    
    init(avatarImageUrl: String) {
        self.avatarImageUrl = avatarImageUrl
    }
    
    var body : some View {
        HStack(spacing: 4) {
            OptionalImage(uiImage: imageProvider.get(from: avatarImageUrl))
                .frame(width: 80, height: 80)
                .clipShape(Circle())
                .background(Circle().stroke(Color(#colorLiteral(red: 0.2235673666, green: 0.2313228846, blue: 0.2665858865, alpha: 1)), lineWidth: 4))
                .offset(y: -10)
                .padding(.trailing, 10)
            Spacer()
            HStack {
                HStack(spacing: 4) {
                    Button(action: {
                        isFollowing.toggle()
                    }) {
                        HStack {
                            Group {
                                if isFollowing {
                                    Text("取消关注")
                                } else {
                                    Image("icon_personal_add_little")
                                    Text("关注")
                                }
                            }
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        
                    }
                    .frame(minWidth: isFollowing ? 0 : followButtonWidth, maxWidth: followButtonWidth, maxHeight: .infinity)
                    .background(isFollowing ? Color(#colorLiteral(red: 0.2235673666, green: 0.2313228846, blue: 0.2665858865, alpha: 1)) : Color(#colorLiteral(red: 0.9308438301, green: 0.1624214649, blue: 0.3100395203, alpha: 1)))
                    .cornerRadius(5)
                    .animation(.default, value: isFollowing)
                    Button(action: {
                        
                    }) {
                        Image("im_x_profile_send_msg_btn_icon19x19")
                            .frame(width: 40, height: 40)
                            .background(Color(#colorLiteral(red: 0.2235673666, green: 0.2313228846, blue: 0.2665858865, alpha: 1)))
                            .cornerRadius(5)
                    }
                    .buttonStyle(PlainButtonStyle())
                    .animation(.default, value: isFollowing)
                }
            }
            .frame(width: followButtonWidth, height: 40, alignment: .leading)
            .foregroundColor(.white)
            
            Button(action: {
                isExpanded.toggle()
            }) {
                Image("playlist_top_arrow14x14")
                    .rotationEffect(.degrees(isExpanded ? 180 : 0))
                    .animation(.default, value: isExpanded)
            }
            .frame(width: 40, height: 40)
            .background(isExpanded ? Color(#colorLiteral(red: 0.2235673666, green: 0.2313228846, blue: 0.2665858865, alpha: 1)) : Color(#colorLiteral(red: 0.9308438301, green: 0.1624214649, blue: 0.3100395203, alpha: 1)))
            .cornerRadius(5)
        }.frame(maxWidth: .infinity, minHeight: 60, maxHeight: 60, alignment: .leading)
    }
    
    private let followButtonWidth: CGFloat = 200
}

extension Int {
    func toMusicDurationString() -> String{
        let minute = self / 60 % 60
        let second = self % 60
        // return formated string
        return String(format: "%02i:%02i", minute, second)
    }
}


// MARK: - Support view preference modifier
//struct ViewOffsetKey: PreferenceKey {
//    typealias Value = CGFloat
//    static var defaultValue = CGFloat.zero
//    static func reduce(value: inout Value, nextValue: () -> Value) {
//        value += nextValue()
//    }
//}

//struct ViewHeightKey: PreferenceKey {
//    static var defaultValue: CGFloat = 0
//
//    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
//        value = nextValue()
//    }
//
//    typealias Value = CGFloat
//}

struct ExperimentView: View {
    var body: some View {
        Text("👤Ta正在关注你哦\n网络歌手\\平面模特\\个人舞蹈练习生\n路人视角在喜欢列表")
    }
}


struct ProfileView_Previews: PreviewProvider {
    static var previews: some View {
        FollowTheUserView(avatarImageUrl: "")
            .previewDevice("iPhone 6s")
            .border(Color.red)
    }
}
